package session;

import java.io.IOException;
import java.util.LinkedList;

import data.Data;
import data.Logout;

public class QueueThread {

	private Session session;
	private LinkedList<Data> sendqueue=new LinkedList<Data>();
	private LinkedList<byte[]> recvqueue=new LinkedList<byte[]>();
	public QueueThread(Session session) {
		this.session=session;
	}
	
	ReceiveThread recvth = new ReceiveThread();
	SendThread sendth = new SendThread();
	
	public class ReceiveThread extends Thread {
		public void run() {
			while(!session.terminated()) {
				//System.out.println("Receive:");
				try {
					session.recvudp();
					//System.out.println("Received " + data.length +" Bytes: ");
				} catch (Exception e) {
					System.err.println("Error while performing recv");
					e.printStackTrace();
				}
			}
			System.out.println("Receive routine terminated");
		}
	}
	
	public class SendThread extends Thread {
		public void run() {
			while(!session.terminated()) {
				try {
					//ATM use callback function, needs to be handled more sophisticated
					if(!sendqueue.isEmpty())
						session.sendudp(sendqueue.poll().getDataWithHeader());
				} catch (IOException e) {
					System.err.println("Error while performing send");
					e.printStackTrace();
				}
			}
			//Send Logout Packet
			try {
				session.sendudp(new Logout().getDataWithHeader());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Send routine terminated");
		}
	}
	
	public synchronized void putsend(Data data) {
		sendqueue.add(data);
	}
	
	public synchronized void putrecv(byte[] data) {
		recvqueue.add(data);
	}
	
	public void start() {
		this.sendth.start();
		this.recvth.start();
	}
}
